//
// Created by 11510 on 2025/10/2.
//

#include "ServiceCommand.h"

xclib_client::ServiceCommand::ServiceCommand(CommandContext ctx) : ICommand("service", ctx) {}

std::optional<std::future<int>> xclib_client::ServiceCommand::run(const std::vector<std::string> &args, bool wait) {
    cxxopts::Options options("service", "service <subcommand> [options]");
    options.add_options()
            ("help", "help");
    if (args.size() < 2) {
        std::cout << "service requires a subcommand: heartbeat | logger\n";
        return std::nullopt;
    }
    std::string sub = args[1];
    if (sub == "heartbeat") {
        cxxopts::Options o("service heartbeat", "heartbeat control");
        o.add_options()("on", "on")("off", "off")("help", "help");
        std::vector<std::string> subargs(args.begin() + 2, args.end());
        try {
            auto r = parseOptions(options, args);
            if (r.count("help")) {
                std::cout << o.help() << "\n";
                return std::nullopt;
            }
            if (r.count("on"))
                std::cout << "heartbeat on\n";
            else if (r.count("off"))
                std::cout << "heartbeat off\n";
            else
                std::cout << "heartbeat requires --on or --off\n";
        } catch (const cxxopts::exceptions::exception &e) { std::cerr << "service heartbeat: " << e.what() << "\n"; }
    } else if (sub == "logger") {
        cxxopts::Options o("service logger", "logger control");
        o.add_options()("on", "on")("off", "off")("help", "help");
        std::vector<std::string> subargs(args.begin() + 2, args.end());
        try {
            auto r = parseOptions(o, args);
            if (r.count("help")) {
                std::cout << o.help() << "\n";
                return std::nullopt;
            }
            if (r.count("on")) std::cout << "logger on\n";
            else if (r.count("off")) std::cout << "logger off\n";
            else
                std::cout << "logger requires --on or --off\n";
        } catch (const cxxopts::exceptions::exception &e) { std::cerr << "service logger: " << e.what() << "\n"; }
    } else {
        std::cout << "unknown service subcommand: " << sub << "\n";
    }
    return std::nullopt;
}

std::string xclib_client::ServiceCommand::shortHelp() const { return "service <heartbeat|logger> --on|--off"; }

std::string xclib_client::ServiceCommand::longHelp() const { return "service heartbeat --on|--off\nservice logger --on|--off"; }